<?php

// 定义推送API处理函数
function handle_push_api($act) {
    global $userrow, $DB, $islogin;
    
    // 添加调试信息
    error_log("处理推送API请求: $act, 用户ID: " . ($userrow ? $userrow['uid'] : 'null'));
    
    // 检查必要的全局变量是否存在
    if (!isset($DB) || !$DB) {
        error_log("错误: 数据库对象不存在");
        exit(json_encode(['code' => -1, 'msg' => '系统错误: 数据库连接失败']));
    }
    
    if (!isset($userrow) || !$userrow) {
        error_log("错误: 用户信息不存在");
        exit(json_encode(['code' => -10, 'msg' => '请先登录']));
    }
    
    // 设置 WxPusher Token
    $Token = 'AT_OdR3phm4adgkF8sueY1PXmNS9niFiDip'; // 请替换为实际的Token
    $wxpusher = new Wxpusher($Token);
    
    // 检查用户是否登录
    if($islogin != 1){
        error_log("错误: 用户未登录, islogin = " . var_export($islogin, true));
        exit(json_encode(['code' => -10, 'msg' => '请先登录']));
    }
    
    try {
        // 处理不同的请求
        switch($act){
            
            // 获取推送设置
            case 'getPushSettings':
                // 获取用户的推送设置
                $user = $userrow['user']; // 当前登录用户
                $uid = $userrow['uid'];
                
                // 检查用户表是否有推送字段 - 直接查询字段结构
                $requiredFields = ['pushUid', 'orderComplete', 'sysNotice', 'balanceLow', 'loginSecurity',  'orderExceptionNotice', 'orderRefundNotice', 'newAgentNotice', 'examStartNotice', 'touristOrderNotice'];
                $existingFields = [];
                
                // 获取表结构
                $tableStructure = $DB->query("DESCRIBE qingka_wangke_user");
                if (!$tableStructure) {
                    error_log("无法获取表结构: " . $DB->error());
                    exit(json_encode(['code' => -1, 'msg' => '系统错误：无法获取用户数据结构']));
                }
                
                // 检查哪些字段存在
                while($row = $DB->fetch($tableStructure)) {
                    if (in_array($row['Field'], $requiredFields)) {
                        $existingFields[$row['Field']] = true;
                    }
                }
                
                error_log("现有字段: " . json_encode($existingFields));
                
                // 查询用户最新的推送设置
                $settings = $DB->get_row("SELECT 
                    pushUid, 
                    orderComplete, 
                    sysNotice, 
                    balanceLow, 
                    loginSecurity,
                   
                    orderExceptionNotice,
                    orderRefundNotice,
                    newAgentNotice,
                    examStartNotice,
                    touristOrderNotice
                FROM qingka_wangke_user WHERE uid='$uid'");
                
                error_log("获取到的推送设置: " . json_encode($settings));
                
                if($settings){
                    $data = [
                        'code' => 1,
                        'data' => [
                            'account' => $user,
                            'pushUid' => $settings['pushUid'],
                            'orderComplete' => isset($settings['orderComplete']) ? $settings['orderComplete'] : '1',
                            'sysNotice' => isset($settings['sysNotice']) ? $settings['sysNotice'] : '0',
                            'balanceLow' => isset($settings['balanceLow']) ? $settings['balanceLow'] : '1',
                            'loginSecurity' => isset($settings['loginSecurity']) ? $settings['loginSecurity'] : '1',
                           
                            'orderExceptionNotice' => isset($settings['orderExceptionNotice']) ? $settings['orderExceptionNotice'] : '1',
                            'orderRefundNotice' => isset($settings['orderRefundNotice']) ? $settings['orderRefundNotice'] : '1',
                            'newAgentNotice' => isset($settings['newAgentNotice']) ? $settings['newAgentNotice'] : '1',
                            'examStartNotice' => isset($settings['examStartNotice']) ? $settings['examStartNotice'] : '1',
                            'touristOrderNotice' => isset($settings['touristOrderNotice']) ? $settings['touristOrderNotice'] : '0'
                        ],
                        'fields_status' => [
                            'orderComplete' => isset($existingFields['orderComplete']),
                            'sysNotice' => isset($existingFields['sysNotice']),
                            'balanceLow' => isset($existingFields['balanceLow']),
                            'loginSecurity' => isset($existingFields['loginSecurity']),
                          
                            'orderExceptionNotice' => isset($existingFields['orderExceptionNotice']),
                            'orderRefundNotice' => isset($existingFields['orderRefundNotice']),
                            'newAgentNotice' => isset($existingFields['newAgentNotice']),
                            'examStartNotice' => isset($existingFields['examStartNotice']),
                            'touristOrderNotice' => isset($existingFields['touristOrderNotice'])
                        ]
                    ];
                } else {
                    error_log("未找到用户推送设置，用户ID: $uid");
                    $data = ['code' => -1, 'msg' => '获取推送设置失败'];
                }
                
                exit(json_encode($data));
                break;
            
            // 保存推送设置
            case 'savePushSettings':
                // 验证参数的有效性
                $validValues = ['0', '1']; // 只允许0或1的值
                
                // 获取用户请求中的参数，并进行验证
                $orderComplete = isset($_POST['orderComplete']) && in_array($_POST['orderComplete'], $validValues) 
                    ? daddslashes($_POST['orderComplete']) 
                    : null;
                
                $sysNotice = isset($_POST['sysNotice']) && in_array($_POST['sysNotice'], $validValues) 
                    ? daddslashes($_POST['sysNotice']) 
                    : null;
                
                $balanceLow = isset($_POST['balanceLow']) && in_array($_POST['balanceLow'], $validValues) 
                    ? daddslashes($_POST['balanceLow']) 
                    : null;
                
                $loginSecurity = isset($_POST['loginSecurity']) && in_array($_POST['loginSecurity'], $validValues) 
                    ? daddslashes($_POST['loginSecurity']) 
                    : null;
                
                
                $orderExceptionNotice = isset($_POST['orderExceptionNotice']) && in_array($_POST['orderExceptionNotice'], $validValues) 
                    ? daddslashes($_POST['orderExceptionNotice']) 
                    : null;
                
                $orderRefundNotice = isset($_POST['orderRefundNotice']) && in_array($_POST['orderRefundNotice'], $validValues) 
                    ? daddslashes($_POST['orderRefundNotice']) 
                    : null;
                
                $newAgentNotice = isset($_POST['newAgentNotice']) && in_array($_POST['newAgentNotice'], $validValues) 
                    ? daddslashes($_POST['newAgentNotice']) 
                    : null;
                
                $examStartNotice = isset($_POST['examStartNotice']) && in_array($_POST['examStartNotice'], $validValues) 
                    ? daddslashes($_POST['examStartNotice']) 
                    : null;
                
                $touristOrderNotice = isset($_POST['touristOrderNotice']) && in_array($_POST['touristOrderNotice'], $validValues) 
                    ? daddslashes($_POST['touristOrderNotice']) 
                    : null;
                
                $uid = $userrow['uid'];
                
                // 检查表中哪些字段真实存在
                $requiredFields = ['orderComplete', 'sysNotice', 'balanceLow', 'loginSecurity', 'orderExceptionNotice', 'orderRefundNotice', 'newAgentNotice', 'examStartNotice', 'touristOrderNotice'];
                $existingFields = [];
                
                $tableStructure = $DB->query("DESCRIBE qingka_wangke_user");
                if (!$tableStructure) {
                    error_log("无法获取表结构: " . $DB->error());
                    exit(json_encode(['code' => -1, 'msg' => '系统错误：无法获取用户数据结构']));
                }
                
                while($row = $DB->fetch($tableStructure)) {
                    if (in_array($row['Field'], $requiredFields)) {
                        $existingFields[$row['Field']] = true;
                    }
                }
                
                error_log("保存设置 - 现有字段: " . json_encode($existingFields));
                error_log("请求参数: orderComplete=$orderComplete, sysNotice=$sysNotice, balanceLow=$balanceLow, loginSecurity=$loginSecurity, orderExceptionNotice=$orderExceptionNotice, orderRefundNotice=$orderRefundNotice, newAgentNotice=$newAgentNotice, examStartNotice=$examStartNotice, touristOrderNotice=$touristOrderNotice");
                
                // 构建更新SQL，只包含有效的字段和有效的值
                $updateParts = [];
                
                if($orderComplete !== null && isset($existingFields['orderComplete'])) {
                    $updateParts[] = "orderComplete='$orderComplete'";
                }
                
                if($sysNotice !== null && isset($existingFields['sysNotice'])) {
                    $updateParts[] = "sysNotice='$sysNotice'";
                }
                
                if($balanceLow !== null && isset($existingFields['balanceLow'])) {
                    $updateParts[] = "balanceLow='$balanceLow'";
                }
                
                if($loginSecurity !== null && isset($existingFields['loginSecurity'])) {
                    $updateParts[] = "loginSecurity='$loginSecurity'";
                }
                
                
                if($orderExceptionNotice !== null && isset($existingFields['orderExceptionNotice'])) {
                    $updateParts[] = "orderExceptionNotice='$orderExceptionNotice'";
                }
                
                if($orderRefundNotice !== null && isset($existingFields['orderRefundNotice'])) {
                    $updateParts[] = "orderRefundNotice='$orderRefundNotice'";
                }
                
                if($newAgentNotice !== null && isset($existingFields['newAgentNotice'])) {
                    $updateParts[] = "newAgentNotice='$newAgentNotice'";
                }
                
                if($examStartNotice !== null && isset($existingFields['examStartNotice'])) {
                    $updateParts[] = "examStartNotice='$examStartNotice'";
                }
                
                if($touristOrderNotice !== null && isset($existingFields['touristOrderNotice'])) {
                    $updateParts[] = "touristOrderNotice='$touristOrderNotice'";
                }
                
                // 如果没有有效的更新部分，则返回错误
                if(empty($updateParts)) {
                    error_log("没有有效的更新参数");
                    exit(json_encode([
                        'code' => -1, 
                        'msg' => '没有有效的设置参数',
                        'fields_status' => [
                            'orderComplete' => isset($existingFields['orderComplete']),
                            'sysNotice' => isset($existingFields['sysNotice']),
                            'balanceLow' => isset($existingFields['balanceLow']),
                            'loginSecurity' => isset($existingFields['loginSecurity']),
                          
                            'orderExceptionNotice' => isset($existingFields['orderExceptionNotice']),
                            'orderRefundNotice' => isset($existingFields['orderRefundNotice']),
                            'newAgentNotice' => isset($existingFields['newAgentNotice']),
                            'examStartNotice' => isset($existingFields['examStartNotice']),
                            'touristOrderNotice' => isset($existingFields['touristOrderNotice'])
                        ]
                    ]));
                }
                
                $sql = "UPDATE qingka_wangke_user SET " . implode(", ", $updateParts) . " WHERE uid='$uid'";
                error_log("执行SQL: $sql");
                
                $result = $DB->query($sql);
                
                if($result){
                    // 更新成功后，重新获取当前用户的设置，确保返回最新值
                    $settings = $DB->get_row("SELECT 
                        orderComplete, 
                        sysNotice, 
                        balanceLow, 
                        loginSecurity,
                      
                        orderExceptionNotice,
                        orderRefundNotice,
                        newAgentNotice,
                        examStartNotice,
                        touristOrderNotice
                    FROM qingka_wangke_user WHERE uid='$uid'");
                    
                    exit(json_encode([
                        'code' => 1, 
                        'msg' => '推送设置保存成功', 
                        'data' => [
                            'orderComplete' => isset($settings['orderComplete']) ? $settings['orderComplete'] : '1',
                            'sysNotice' => isset($settings['sysNotice']) ? $settings['sysNotice'] : '0',
                            'balanceLow' => isset($settings['balanceLow']) ? $settings['balanceLow'] : '1',
                            'loginSecurity' => isset($settings['loginSecurity']) ? $settings['loginSecurity'] : '1',
                          
                            'orderExceptionNotice' => isset($settings['orderExceptionNotice']) ? $settings['orderExceptionNotice'] : '1',
                            'orderRefundNotice' => isset($settings['orderRefundNotice']) ? $settings['orderRefundNotice'] : '1',
                            'newAgentNotice' => isset($settings['newAgentNotice']) ? $settings['newAgentNotice'] : '1',
                            'examStartNotice' => isset($settings['examStartNotice']) ? $settings['examStartNotice'] : '1',
                            'touristOrderNotice' => isset($settings['touristOrderNotice']) ? $settings['touristOrderNotice'] : '0'
                        ],
                        'fields_status' => [
                            'orderComplete' => isset($existingFields['orderComplete']),
                            'sysNotice' => isset($existingFields['sysNotice']),
                            'balanceLow' => isset($existingFields['balanceLow']),
                            'loginSecurity' => isset($existingFields['loginSecurity']),
                          
                            'orderExceptionNotice' => isset($existingFields['orderExceptionNotice']),
                            'orderRefundNotice' => isset($existingFields['orderRefundNotice']),
                            'newAgentNotice' => isset($existingFields['newAgentNotice']),
                            'examStartNotice' => isset($existingFields['examStartNotice']),
                            'touristOrderNotice' => isset($existingFields['touristOrderNotice'])
                        ]
                    ]));
                } else {
                    error_log("保存推送设置失败，错误: " . $DB->error());
                    exit(json_encode(['code' => -1, 'msg' => '推送设置保存失败']));
                }
                break;
            
            // 登录安全提醒测试
            case 'testLoginSecurityPush':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid, loginSecurity FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                // 检查用户是否开启了登录安全提醒
                if(isset($userPushUid['loginSecurity']) && $userPushUid['loginSecurity'] !== '1') {
                    exit(json_encode(['code' => -1, 'msg' => '您已关闭登录安全提醒功能，请先开启']));
                }
                
                // 构建测试登录信息
                $ip = real_ip();
                $ua = $_SERVER['HTTP_USER_AGENT'] ?? '未知';
                $location = getIpLocation($ip);
                $device = getDeviceInfo($ua);
                
                $loginInfo = [
                    'ip' => $ip,
                    'location' => $location,
                    'device' => $device,
                    'time' => date('Y-m-d H:i:s'),
                    'is_test' => true
                ];
                
                $result = sendLoginSecurityAlert($wxpusher, $userPushUid['pushUid'], $loginInfo);
                
                if($result){
                    // 记录测试操作
                    wlog($uid, "登录安全提醒测试", "IP: $ip, 设备: $device", "0");
                    
                    exit(json_encode(['code' => 1, 'msg' => '登录安全提醒测试推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '登录安全提醒测试推送发送失败']));
                }
                break;
            
            // 登录安全提醒测试 - 别名（匹配push_manage.php中的调用）
            case 'testLoginSecurityAlert':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid, loginSecurity FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                // 检查用户是否开启了登录安全提醒
                if(isset($userPushUid['loginSecurity']) && $userPushUid['loginSecurity'] !== '1') {
                    exit(json_encode(['code' => -1, 'msg' => '您已关闭登录安全提醒功能，请先开启']));
                }
                
                // 构建测试登录信息
                $ip = real_ip();
                $ua = $_SERVER['HTTP_USER_AGENT'] ?? '未知';
                $location = getIpLocation($ip);
                $device = getDeviceInfo($ua);
                
                $loginInfo = [
                    'ip' => $ip,
                    'location' => $location,
                    'device' => $device,
                    'time' => date('Y-m-d H:i:s'),
                    'is_test' => true
                ];
                
                $result = sendLoginSecurityAlert($wxpusher, $userPushUid['pushUid'], $loginInfo);
                
                if($result){
                    // 记录测试操作
                    wlog($uid, "登录安全提醒测试", "IP: $ip, 设备: $device", "0");
                    
                    exit(json_encode(['code' => 1, 'msg' => '登录安全提醒测试推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '登录安全提醒测试推送发送失败']));
                }
                break;
            
            // 记录登录信息
            case 'recordLogin':
                $uid = $userrow['uid'];
                $ip = isset($_POST['ip']) ? daddslashes($_POST['ip']) : real_ip();
                $ua = isset($_POST['user_agent']) ? daddslashes($_POST['user_agent']) : ($_SERVER['HTTP_USER_AGENT'] ?? '未知');
                
                $result = recordLoginAndCheckSecurity($DB, $wxpusher, $uid, $ip, $ua);
                exit(json_encode(['code' => 1, 'data' => $result]));
                break;
                
            // 获取登录安全记录
            case 'getLoginRecords':
                $uid = $userrow['uid'];
                $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
                
                $records = getLoginRecords($DB, $uid, $limit);
                exit(json_encode(['code' => 1, 'data' => $records]));
                break;
            
            // 获取推送记录
            case 'getPushLogs':
                $type = isset($_GET['type']) ? daddslashes($_GET['type']) : 'recent';
                $limit = 20; // 默认显示20条记录
                $uid = $userrow['uid'];
                
                // 检查表是否存在
                $tableExists = $DB->query("SHOW TABLES LIKE 'push_logs'");
                if (!$DB->fetch($tableExists)) {
                    error_log("表不存在: push_logs");
                    exit(json_encode(['code' => 1, 'data' => []]));
                }
                
                // 构建SQL查询语句
                $whereSql = "WHERE uid='$uid'";
                
                if($type == 'order'){
                    $whereSql .= " AND type='order'";
                } elseif($type == 'system'){
                    $whereSql .= " AND type='system'";
                } elseif($type == 'security'){
                    $whereSql .= " AND type='security'";
                }
                
                // 查询推送记录
                $sql = "SELECT * FROM push_logs $whereSql ORDER BY push_time DESC LIMIT $limit";
                error_log("执行SQL: $sql");
                
                $query = $DB->query($sql);
                $logs = [];
                
                if($query) {
                    while($row = $DB->fetch($query)){
                        $logs[] = $row;
                    }
                } else {
                    error_log("查询推送记录失败，错误: " . $DB->error());
                }
                
                exit(json_encode(['code' => 1, 'data' => $logs]));
                break;
            
            // 获取微信绑定二维码
            case 'getBindQrcode':
                // 生成二维码，包含用户ID信息
                $uid = $userrow['uid'];
                $extra = json_encode(['uid' => $uid]);
                $qrcodeData = $wxpusher->Qrcreate($extra, 1800); // 30分钟有效
                
                error_log("生成二维码结果: " . json_encode($qrcodeData));
                
                if(is_array($qrcodeData)){
                    exit(json_encode([
                        'code' => 1,
                        'data' => [
                            'code' => $qrcodeData['code'],
                            'url' => $qrcodeData['url'],
                            'expires' => $qrcodeData['expires']
                        ]
                    ]));
                } else {
                    error_log("二维码生成失败");
                    exit(json_encode(['code' => -1, 'msg' => '二维码生成失败']));
                }
                break;
            
            // 检查绑定状态
            case 'checkBindStatus':
                $code = isset($_GET['code']) ? daddslashes($_GET['code']) : '';
                $uid = $userrow['uid'];
                
                if(empty($code)){
                    exit(json_encode(['code' => -1, 'msg' => '参数错误']));
                }
                
                // 调用WxPusher查询扫码用户的UID
                $pushUid = $wxpusher->getScanQrcodeUid($code);
                error_log("检查绑定状态，扫码用户UID: " . ($pushUid ? $pushUid : "未扫码"));
                
                if($pushUid){
                    // 更新用户表中的pushUid
                    $updateResult = $DB->query("UPDATE qingka_wangke_user SET pushUid='$pushUid' WHERE uid='$uid'");
                    error_log("更新用户pushUid结果: " . ($updateResult ? "成功" : "失败"));
                    
                    exit(json_encode(['code' => 1, 'msg' => '绑定成功']));
                } else {
                    exit(json_encode(['code' => 0, 'msg' => '未扫码']));
                }
                break;
            
            // 解除绑定
            case 'unbindPush':
                $uid = $userrow['uid'];
                // 清空用户的pushUid
                $result = $DB->query("UPDATE qingka_wangke_user SET pushUid=NULL WHERE uid='$uid'");
                error_log("解除绑定结果: " . ($result ? "成功" : "失败"));
                
                exit(json_encode(['code' => 1, 'msg' => '解除绑定成功']));
                break;
            
            // 推送测试
            case 'testPush':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                // 检查是否请求推送最新公告
                $pushType = isset($_GET['type']) ? daddslashes($_GET['type']) : 'test';
                
                if ($pushType === 'announcement') {
                    // 获取最新公告并推送
                    $announcement = getLatestAnnouncement();
                    if (!$announcement) {
                        exit(json_encode(['code' => -1, 'msg' => '没有可推送的系统公告']));
                    }
                    
                    $result = sendAnnouncementPush($wxpusher, $userPushUid['pushUid'], $announcement);
                    
                    if($result){
                        exit(json_encode(['code' => 1, 'msg' => '系统公告推送成功']));
                    } else {
                        exit(json_encode(['code' => -1, 'msg' => '系统公告推送失败']));
                    }
                } else {
                    // 默认发送测试消息
                    // 构建测试推送内容
                    $content = "🔔 推送测试\n\n";
                    $content .= "这是一条测试推送消息，如果您收到本条消息，表示推送功能正常。\n\n";
                    $content .= "⏰ 推送时间：" . date("Y-m-d H:i:s");
                    
                    // 发送推送
                    $pushUid = $userPushUid['pushUid'];
                    $result = $wxpusher->send($content, '推送测试', '2', 'true', $pushUid);
                    error_log("测试推送结果: " . ($result === true ? "成功" : "失败"));
                    
                    if($result === true){
                        // 记录推送日志
                        try {
                            $logResult = $DB->query("INSERT INTO push_logs (uid, type, title, content, status, push_time) 
                                       VALUES ('$uid', 'system', '推送测试', '测试消息', '1', NOW())");
                            error_log("记录推送日志结果: " . ($logResult ? "成功" : "失败"));
                        } catch (Exception $e) {
                            error_log("记录推送日志异常: " . $e->getMessage());
                        }
                        
                        exit(json_encode(['code' => 1, 'msg' => '测试推送发送成功']));
                    } else {
                        exit(json_encode(['code' => -1, 'msg' => '测试推送发送失败']));
                    }
                }
                break;
            
            // 获取最新系统公告
            case 'getLatestAnnouncement':
                $announcement = getLatestAnnouncement();
                exit(json_encode(['code' => 1, 'data' => $announcement]));
                break;
            
            // 发送系统公告推送
            case 'sendAnnouncementPush':
                $announcement = isset($_POST['announcement']) ? json_decode($_POST['announcement'], true) : null;
                $pushUid = $userrow['pushUid'];
                
                if (sendAnnouncementPush($wxpusher, $pushUid, $announcement)) {
                    exit(json_encode(['code' => 1, 'msg' => '系统公告推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '系统公告推送发送失败']));
                }
                break;
            
            // 发送系统公告推送
            case 'sendSystemNoticePush':
                $title = isset($_POST['title']) ? daddslashes($_POST['title']) : '';
                $content = isset($_POST['content']) ? daddslashes($_POST['content']) : '';
                $users = isset($_POST['users']) ? json_decode($_POST['users'], true) : [];
                
                if (empty($title) || empty($content) || empty($users)) {
                    exit(json_encode(['code' => -1, 'msg' => '参数错误']));
                }
                
                $result = sendSystemNoticePush($wxpusher, $title, $content, $users);
                exit(json_encode(['code' => 1, 'data' => $result]));
                break;
            
            // 获取系统公告列表
            case 'get_announcements':
                $announcements = get_announcements();
                exit(json_encode(['code' => 1, 'data' => $announcements]));
                break;
            
            // 发送余额不足预警推送
            case 'sendBalanceLowAlert':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                $result = sendBalanceLowAlert($wxpusher, $userPushUid['pushUid'], $userrow, false);
                
                if($result){
                    exit(json_encode(['code' => 1, 'msg' => '余额不足预警推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '余额不足预警推送发送失败']));
                }
                break;
                
            // 检查用户余额并发送预警
            case 'checkBalanceAndAlert':
                $threshold = isset($_GET['threshold']) ? floatval($_GET['threshold']) : 10;
                $uid = isset($_GET['uid']) ? intval($_GET['uid']) : $userrow['uid'];
                
                $result = checkUserBalanceAndAlert($DB, $wxpusher, $uid, $threshold);
                exit(json_encode(['code' => 1, 'data' => $result]));
                break;
            
            // 余额不足推送测试
            case 'testBalanceLow':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                // 构建一个用于测试的用户信息对象，使用用户实际余额
                $testUserInfo = $userrow;
                // 临时修改余额为低值，仅用于显示
                $testUserInfo['money'] = 5.00;
                
                $result = sendBalanceLowAlert($wxpusher, $userPushUid['pushUid'], $testUserInfo, true);
                
                if($result){
                    exit(json_encode(['code' => 1, 'msg' => '余额不足预警测试推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '余额不足预警测试推送发送失败']));
                }
                break;
            
            // 手动触发余额检查并发送预警
            case 'manualBalanceCheck':
                if ($userrow['uid'] != 1) {
                    exit(json_encode(['code' => -1, 'msg' => '只有管理员可以执行此操作']));
                }
                
                $uid = isset($_GET['uid']) ? intval($_GET['uid']) : 0;
                $threshold = isset($_GET['threshold']) ? floatval($_GET['threshold']) : 10;
                
                if ($uid <= 0) {
                    exit(json_encode(['code' => -1, 'msg' => '请指定有效的用户ID']));
                }
                
                // 查询用户信息
                $userInfo = $DB->get_row("SELECT uid, user, name, money, pushUid, balanceLow FROM qingka_wangke_user WHERE uid='$uid'");
                
                if (!$userInfo) {
                    exit(json_encode(['code' => -1, 'msg' => '用户不存在']));
                }
                
                if (empty($userInfo['pushUid'])) {
                    exit(json_encode(['code' => -1, 'msg' => '该用户未绑定微信推送']));
                }
                
                if ($userInfo['balanceLow'] !== '1') {
                    exit(json_encode(['code' => -1, 'msg' => '该用户已关闭余额预警通知']));
                }
                
                // 执行余额检查
                $result = checkUserBalanceAndAlert($DB, $wxpusher, $uid, $threshold);
                exit(json_encode(['code' => 1, 'data' => $result]));
                break;
            
          
            
            // 测试订单异常通知
            case 'testOrderExceptionNotice':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid, orderExceptionNotice FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                // 检查用户是否开启了订单异常通知
                if(isset($userPushUid['orderExceptionNotice']) && $userPushUid['orderExceptionNotice'] !== '1') {
                    exit(json_encode(['code' => -1, 'msg' => '您已关闭订单异常通知功能，请先开启']));
                }
                
                // 构建测试订单信息
                $orderInfo = [
                    'oid' => rand(10000, 99999),
                    'kcname' => '测试课程名称',
                    'user' => 'testuser' . rand(100, 999),
                    'school' => '测试学校',
                    'process' => '登录失败，账号密码错误',
                    'time' => date('Y-m-d H:i:s'),
                    'is_test' => true
                ];
                
                $result = sendOrderExceptionNotice($wxpusher, $userPushUid['pushUid'], $orderInfo);
                
                if($result){
                    // 记录测试操作
                    wlog($uid, "订单异常通知测试", "测试成功", "0");
                    
                    exit(json_encode(['code' => 1, 'msg' => '订单异常通知测试推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '订单异常通知测试推送发送失败']));
                }
                break;
            
            // 测试订单退款通知
            case 'testOrderRefundNotice':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid, orderRefundNotice FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                // 检查用户是否开启了订单退款通知
                if(isset($userPushUid['orderRefundNotice']) && $userPushUid['orderRefundNotice'] !== '1') {
                    exit(json_encode(['code' => -1, 'msg' => '您已关闭订单退款通知功能，请先开启']));
                }
                
                // 构建测试订单信息
                $orderInfo = [
                    'oid' => rand(10000, 99999),
                    'kcname' => '测试课程名称',
                    'fees' => rand(10, 100) . '.00',
                    'refund_reason' => '用户主动申请退款',
                    'refund_time' => date('Y-m-d H:i:s'),
                    'is_test' => true
                ];
                
                $result = sendOrderRefundNotice($wxpusher, $userPushUid['pushUid'], $orderInfo);
                
                if($result){
                    // 记录测试操作
                    wlog($uid, "订单退款通知测试", "测试成功", "0");
                    
                    exit(json_encode(['code' => 1, 'msg' => '订单退款通知测试推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '订单退款通知测试推送发送失败']));
                }
                break;
            
            // 测试新增代理通知
            case 'testNewAgentNotice':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid, newAgentNotice FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                // 检查用户是否开启了新增代理通知
                if(isset($userPushUid['newAgentNotice']) && $userPushUid['newAgentNotice'] !== '1') {
                    exit(json_encode(['code' => -1, 'msg' => '您已关闭新增代理通知功能，请先开启']));
                }
                
                // 构建测试代理信息
                $agentInfo = [
                    'name' => '测试代理',
                    'user' => 'agent' . rand(1000, 9999),
                    'time' => date('Y-m-d H:i:s'),
                    'uuid' => $uid, // 上级代理ID
                    'ip' => '未知IP',
                    'is_test' => true
                ];
                
                $result = sendNewAgentNotice($wxpusher, $userPushUid['pushUid'], $agentInfo);
                
                if($result){
                    // 记录测试操作
                    wlog($uid, "新增代理通知测试", "测试成功", "0");
                    
                    exit(json_encode(['code' => 1, 'msg' => '新增代理通知测试推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '新增代理通知测试推送发送失败']));
                }
                break;
            
            // 发送考试开始提醒
            case 'sendExamStartNotice':
                $examInfo = isset($_POST['examInfo']) ? json_decode($_POST['examInfo'], true) : null;
                $pushUid = $userrow['pushUid'];
                
                if (sendExamStartNotice($wxpusher, $pushUid, $examInfo)) {
                    exit(json_encode(['code' => 1, 'msg' => '考试开始提醒推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '考试开始提醒推送发送失败']));
                }
                break;
            
            // 测试考试开始提醒
            case 'testExamStartNotice':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid, examStartNotice FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                // 检查用户是否开启了考试开始提醒
                if(isset($userPushUid['examStartNotice']) && $userPushUid['examStartNotice'] !== '1') {
                    exit(json_encode(['code' => -1, 'msg' => '您已关闭考试开始提醒功能，请先开启']));
                }
                
                // 构建测试考试信息
                $tomorrow = date('Y-m-d H:i:s', strtotime('+1 day'));
                $examInfo = [
                    'oid' => rand(10000, 99999),
                    'kcname' => '测试课程名称',
                    'examStartTime' => $tomorrow,
                    'school' => '测试学校',
                    'user' => 'test' . rand(100, 999),
                    'is_test' => true
                ];
                
                $result = sendExamStartNotice($wxpusher, $userPushUid['pushUid'], $examInfo);
                
                if($result){
                    // 记录测试操作
                    wlog($uid, "考试开始提醒测试", "测试成功", "0");
                    
                    exit(json_encode(['code' => 1, 'msg' => '考试开始提醒测试推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '考试开始提醒测试推送发送失败']));
                }
                break;
            
            // 测试游客订单通知
            case 'testTouristOrderNotice':
                $uid = $userrow['uid'];
                $userPushUid = $DB->get_row("SELECT pushUid, touristOrderNotice FROM qingka_wangke_user WHERE uid='$uid'");
                
                if(!$userPushUid || empty($userPushUid['pushUid'])){
                    exit(json_encode(['code' => -1, 'msg' => '您尚未绑定微信推送']));
                }
                
                // 检查用户是否开启了游客订单通知
                if(isset($userPushUid['touristOrderNotice']) && $userPushUid['touristOrderNotice'] !== '1') {
                    exit(json_encode(['code' => -1, 'msg' => '您已关闭游客订单通知功能，请先开启']));
                }
                
                // 构建测试订单信息
                $orderInfo = [
                    'oid' => rand(10000, 99999),
                    'kcname' => '测试课程名称',
                    'user' => 'testuser' . rand(100, 999),
                    'school' => '测试学校',
                    'status' => '待处理',
                    'time' => date('Y-m-d H:i:s'),
                    'is_test' => true
                ];
                
                $result = sendTouristOrderNotice($wxpusher, $userPushUid['pushUid'], $orderInfo);
                
                if($result){
                    // 记录测试操作
                    wlog($uid, "游客订单通知测试", "测试成功", "0");
                    
                    exit(json_encode(['code' => 1, 'msg' => '游客订单通知测试推送发送成功']));
                } else {
                    exit(json_encode(['code' => -1, 'msg' => '游客订单通知测试推送发送失败']));
                }
                break;
            
            // 默认情况
            default:
                // 不匹配的推送API请求，返回无效操作
                error_log("未知的推送API操作: $act");
                return false;
        }
    } catch (Exception $e) {
        error_log("处理推送API请求异常: " . $e->getMessage());
        exit(json_encode(['code' => -1, 'msg' => '系统错误: ' . $e->getMessage()]));
    }
    
    return true;
}

/**
 * 发送订单完成推送
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $pushUid 用户的推送UID
 * @param array $order 订单信息
 * @return bool 推送结果
 */
function sendOrderCompletePush($wxpusher, $pushUid, $order) {
    global $DB;
    
    // 构建推送内容
    $content = "✅ 订单完成通知\n\n";
    $content .= "📋 订单ID：{$order['oid']}\n";
    $content .= "👤 账号：{$order['user']}\n";
    $content .= "🏫 学校：{$order['school']}\n";
    $content .= "📚 课程名称：{$order['kcname']}\n";
    $content .= "📝 订单状态：{$order['status']}\n";
    $content .= "💡 订单备注：{$order['remarks']}\n";
    
    
    $content .= "\n⏰ 推送时间：" . date("Y-m-d H:i:s");
    
    // 使用Wxpusher发送消息
    $result = $wxpusher->send($content, '订单完成通知', '2', 'true', $pushUid);
    
    // 记录推送日志
    $status = $result === true ? '1' : '0';
    $uid = $order['uid'];
    $oid = $order['oid'];
    $kcname = addslashes($order['kcname']);
    
    $sql = "INSERT INTO push_logs (uid, order_id, type, title, content, status, push_time) 
           VALUES ('$uid', '$oid', 'order', '订单完成通知', '课程：$kcname', '$status', NOW())";
    
    $DB->query($sql);
    
    return $result === true;
}

/**
 * 获取最新系统公告
 * 
 * @return array|null 返回最新公告信息，如果没有则返回null
 */
function getLatestAnnouncement() {
    global $DB;
    
    // 检查公告表是否存在
    $tableExists = $DB->query("SHOW TABLES LIKE 'qingka_wangke_gonggao'");
    if (!$DB->fetch($tableExists)) {
        error_log("表不存在: qingka_wangke_gonggao");
        return null;
    }
    
    // 获取最新的系统公告（状态为1的公告）
    $latestAnnouncement = $DB->get_row("SELECT * FROM qingka_wangke_gonggao WHERE status=1 ORDER BY id DESC LIMIT 1");
    
    if ($latestAnnouncement) {
        return [
            'id' => $latestAnnouncement['id'],
            'title' => $latestAnnouncement['title'],
            'content' => $latestAnnouncement['content'],
            'time' => $latestAnnouncement['time']
        ];
    }
    
    return null;
}

/**
 * 发送系统公告推送
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $pushUid 用户的推送UID
 * @param array $announcement 公告信息
 * @return bool 推送结果
 */
function sendAnnouncementPush($wxpusher, $pushUid, $announcement) {
    global $DB;
    
    if (!$announcement) {
        return false;
    }
    
    // 构建推送内容
    $content = "📢 系统公告\n\n";
    $content .= "📌 标题：{$announcement['title']}\n\n";
    
    // 去除HTML标签，保留纯文本内容
    $plainContent = strip_tags($announcement['content']);
    // 如果内容太长，则截取前200个字符
    if (mb_strlen($plainContent) > 200) {
        $plainContent = mb_substr($plainContent, 0, 200, 'UTF-8') . "...";
    }
    
    $content .= $plainContent . "\n\n";
    $content .= "⏰ 发布时间：" . date("Y-m-d H:i:s", strtotime($announcement['time']));
    
    // 使用Wxpusher发送消息
    $result = $wxpusher->send($content, '系统公告：' . $announcement['title'], '2', 'true', $pushUid);
    
    // 记录推送日志
    $status = $result === true ? '1' : '0';
    $uid = $DB->get_row("SELECT uid FROM qingka_wangke_user WHERE pushUid='$pushUid'")['uid'];
    $title = addslashes($announcement['title']);
    $contentLog = addslashes("系统公告：" . $announcement['title']);
    
    $sql = "INSERT INTO push_logs (uid, type, title, content, status, push_time) 
           VALUES ('$uid', 'system', '$title', '$contentLog', '$status', NOW())";
    
    $DB->query($sql);
    
    return $result === true;
}

/**
 * 发送系统公告推送
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $title 标题
 * @param string $content 内容
 * @param array $users 用户数组，包含uid和pushUid
 * @return array 推送结果
 */
function sendSystemNoticePush($wxpusher, $title, $content, $users) {
    global $DB;
    
    $successCount = 0;
    $failCount = 0;
    
    // 创建一个临时公告对象
    $announcement = [
        'id' => 0,
        'title' => $title,
        'content' => $content,
        'time' => date('Y-m-d H:i:s')
    ];
    
    foreach ($users as $user) {
        if (!empty($user['pushUid'])) {
            // 使用公告推送函数发送消息
            $result = sendAnnouncementPush($wxpusher, $user['pushUid'], $announcement);
            
            if ($result === true) {
                $successCount++;
            } else {
                $failCount++;
            }
        }
    }
    
    return [
        'success' => $successCount,
        'fail' => $failCount
    ];
}

/**
 * 获取系统公告列表
 * 
 * @return array 公告列表
 */
function get_announcements() {
    global $DB;
    
    // 获取分页参数
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $page_size = isset($_GET['page_size']) ? intval($_GET['page_size']) : 10;
    
    // 计算偏移量
    $offset = ($page - 1) * $page_size;
    
    // 检查公告表是否存在
    $tableExists = $DB->query("SHOW TABLES LIKE 'qingka_wangke_gonggao'");
    if (!$DB->fetch($tableExists)) {
        error_log("表不存在: qingka_wangke_gonggao");
        return [];
    }
    
    // 查询公告数据
    $query = $DB->query("SELECT * FROM qingka_wangke_gonggao WHERE status=1 ORDER BY id DESC LIMIT $offset, $page_size");
    $announcements = [];
    
    if ($query) {
        while ($row = $DB->fetch($query)) {
            $announcements[] = [
                'id' => $row['id'],
                'title' => $row['title'],
                'content' => $row['content'],
                'time' => $row['time'],
                'status' => $row['status']
            ];
        }
    }
    
    return $announcements;
}

/**
 * 发送余额不足预警推送
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $pushUid 用户的推送UID
 * @param array $userInfo 用户信息
 * @param bool $isTest 是否为测试消息
 * @return bool 推送结果
 */
function sendBalanceLowAlert($wxpusher, $pushUid, $userInfo, $isTest = false) {
    global $DB;
    
    // 构建推送内容
    $content = "⚠️ " . ($isTest ? "[测试] " : "") . "余额不足预警\n\n";
    $content .= "亲爱的用户，您的账户余额已不足，当前余额：{$userInfo['money']} 积分\n";
    $content .= "为了不影响您的正常使用，请及时充值。\n\n";
    $content .= "💡 充值方式：请联系您的上级代理或直接在网站中充值\n\n";
    $content .= "⏰ 推送时间：" . date("Y-m-d H:i:s");
    
    // 使用Wxpusher发送消息
    $result = $wxpusher->send($content, ($isTest ? '[测试] ' : '') . '余额不足预警通知', '2', 'true', $pushUid);
    
    // 记录推送日志
    $status = $result === true ? '1' : '0';
    $uid = $userInfo['uid'];
    $title = ($isTest ? '[测试] ' : '') . '余额不足预警通知';
    $contentLog = "当前余额：{$userInfo['money']} 积分" . ($isTest ? " (测试消息)" : "");
    
    $sql = "INSERT INTO push_logs (uid, type, title, content, status, push_time) 
           VALUES ('$uid', 'system', '$title', '$contentLog', '$status', NOW())";
    
    $DB->query($sql);
    
    return $result === true;
}

/**
 * 检查用户余额并发送预警
 * 
 * @param object $DB 数据库对象
 * @param object $wxpusher WxPusher对象
 * @param int $uid 用户ID
 * @param float $threshold 余额阈值
 * @return array 处理结果
 */
function checkUserBalanceAndAlert($DB, $wxpusher, $uid, $threshold = 10) {
    // 查询指定用户信息
    $userInfo = $DB->get_row("SELECT uid, user, name, money, pushUid, balanceLow FROM qingka_wangke_user WHERE uid='$uid'");
    
    if (!$userInfo) {
        return ['success' => false, 'msg' => '用户不存在'];
    }
    
    // 如果用户未绑定推送或余额充足或关闭了余额预警，则跳过
    if (empty($userInfo['pushUid']) || $userInfo['money'] >= $threshold || $userInfo['balanceLow'] !== '1') {
        return [
            'success' => false, 
            'msg' => empty($userInfo['pushUid']) ? '用户未绑定推送' : 
                   ($userInfo['balanceLow'] !== '1' ? '用户已关闭余额预警' : '用户余额充足'),
            'balance' => $userInfo['money']
        ];
    }
    
    // 检查是否已经在24小时内发送过预警
    $lastAlert = $DB->get_row("SELECT id FROM push_logs WHERE uid='$uid' AND type='system' AND title='余额不足预警通知' AND push_time > DATE_SUB(NOW(), INTERVAL 24 HOUR) AND status='1'");
    
    if ($lastAlert) {
        return [
            'success' => false, 
            'msg' => '24小时内已发送过预警通知',
            'balance' => $userInfo['money']
        ];
    }
    
    // 发送预警推送
    $result = sendBalanceLowAlert($wxpusher, $userInfo['pushUid'], $userInfo, false);
    
    return [
        'success' => $result,
        'msg' => $result ? '预警通知发送成功' : '预警通知发送失败',
        'balance' => $userInfo['money']
    ];
}


/**
 * 发送订单异常通知
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $pushUid 用户的推送UID
 * @param array $orderInfo 订单信息
 * @return bool 推送结果
 */
function sendOrderExceptionNotice($wxpusher, $pushUid, $orderInfo) {
    global $DB;
    
    // 验证参数
    if(empty($pushUid) || !is_array($orderInfo)) {
        error_log("发送订单异常通知参数无效: pushUid=" . ($pushUid ?? 'null') . ", orderInfo=" . json_encode($orderInfo));
        return false;
    }
    
    // 确保必要的订单信息存在
    $orderInfo['oid'] = $orderInfo['oid'] ?? '未知';
    $orderInfo['kcname'] = $orderInfo['kcname'] ?? '未知课程';
    $orderInfo['user'] = $orderInfo['user'] ?? '未知账号';
    $orderInfo['school'] = $orderInfo['school'] ?? '未知学校';
    $orderInfo['process'] = $orderInfo['process'] ?? '未知错误';
    $orderInfo['time'] = $orderInfo['time'] ?? date('Y-m-d H:i:s');
    
    // 构建推送内容
    $content = "⚠️ " . (isset($orderInfo['is_test']) ? "[测试] " : "") . "订单异常通知\n\n";
    $content .= "您有一个订单出现异常，请及时处理！\n\n";
    $content .= "📋 订单编号：" . $orderInfo['oid'] . "\n";
    $content .= "📚 课程名称：" . $orderInfo['kcname'] . "\n";
    $content .= "🏫 所属学校：" . $orderInfo['school'] . "\n";
    $content .= "👤 课程账号：" . $orderInfo['user'] . "\n";
    $content .= "❌ 异常原因：" . $orderInfo['process'] . "\n";
    $content .= "⏰ 异常时间：" . $orderInfo['time'] . "\n\n";
    $content .= "请登录系统查看详情并处理异常订单。";
    
    $title = (isset($orderInfo['is_test']) ? '[测试] ' : '') . '订单异常通知';
    
    try {
        // 使用Wxpusher发送消息
        $result = $wxpusher->send($content, $title, '2', 'true', $pushUid);
        
        // 如果发送失败，记录错误
        if($result !== true) {
            error_log("发送订单异常通知失败: " . json_encode($result));
            // 如果是WxPusher返回的错误对象，提取错误信息
            if(is_array($result) && isset($result['msg'])) {
                error_log("WxPusher错误: " . $result['msg']);
            }
        }
    } catch (Exception $e) {
        error_log("发送订单异常通知异常: " . $e->getMessage());
        $result = false;
    }
    
    // 记录推送状态
    $status = $result === true ? '1' : '0';
    
    // 查询用户ID
    $uidQuery = $DB->get_row("SELECT uid FROM qingka_wangke_user WHERE pushUid='$pushUid'");
    $uid = $uidQuery ? $uidQuery['uid'] : 0;
    
    $contentLog = "订单:" . $orderInfo['oid'] . ", 课程:" . $orderInfo['kcname'] . ", 异常:" . $orderInfo['process'] . (isset($orderInfo['is_test']) ? " (测试)" : "");
    
    // 使用安全的SQL插入
    $safeTitle = $DB->escape($title);
    $safeContent = $DB->escape($contentLog);
    $orderId = isset($orderInfo['is_test']) ? null : $orderInfo['oid'];
    
    // 尝试插入日志，如果表已经存在
    try {
        $sql = "INSERT INTO push_logs (uid, order_id, type, title, content, status, push_time) 
               VALUES ('$uid', " . ($orderId ? "'$orderId'" : "NULL") . ", 'order_exception', '$safeTitle', '$safeContent', '$status', NOW())";
        
        $logResult = $DB->query($sql);
        if(!$logResult) {
            error_log("记录推送日志失败: " . $DB->error());
        }
    } catch (Exception $e) {
        error_log("记录推送日志异常: " . $e->getMessage());
    }
    
    return $result === true;
}

/**
 * 发送新增代理通知
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $pushUid 用户的推送UID
 * @param array $agentInfo 代理信息
 * @return bool 推送结果
 */
function sendNewAgentNotice($wxpusher, $pushUid, $agentInfo) {
    global $DB;
    
    // 验证参数
    if(empty($pushUid) || !is_array($agentInfo)) {
        error_log("发送新增代理通知参数无效: pushUid=" . ($pushUid ?? 'null') . ", agentInfo=" . json_encode($agentInfo));
        return false;
    }
    
    // 确保必要的代理信息存在
    $agentInfo['name'] = $agentInfo['name'] ?? '未知代理';
    $agentInfo['user'] = $agentInfo['user'] ?? '未知账号';
    $agentInfo['time'] = $agentInfo['time'] ?? date('Y-m-d H:i:s');
    $agentInfo['ip'] = $agentInfo['ip'] ?? '未知IP';
            
    // 获取IP位置信息（添加超时设置为10秒）
    $ip = $agentInfo['ip'];
    $location = '未知位置';
    if(!empty($ip) && $ip != 'unknown') {
        // 先获取IP地址位置信息，再发送通知
        $location = getIpLocation($ip);
        
        // 记录日志
        error_log("新增代理IP信息获取: " . $ip . " -> " . $location);
        
        // 如果位置仍然是IP地址，再尝试一次获取位置
        if($location == $ip) {
            sleep(1); // 等待1秒后重试
            $location = getIpLocation($ip);
        }
    }
    
    // 构建推送内容
    $content = "🎊 " . (isset($agentInfo['is_test']) ? "[测试] " : "") . "新增代理通知\n\n";
    $content .= "您的团队有新代理加入！\n\n";
    $content .= "👤 代理姓名：" . $agentInfo['name'] . "\n";
    $content .= "🔢 登录账号：" . $agentInfo['user'] . "\n";
    $content .= "📍 注册地区：" . $location . "\n";
    $content .= "⏰ 加入时间：" . $agentInfo['time'] . "\n\n";
    $content .= "恭喜您的团队扩大，请继续保持良好发展势头！";
    
    $title = (isset($agentInfo['is_test']) ? '[测试] ' : '') . '新增代理通知';
    
    try {
        // 使用Wxpusher发送消息
        $result = $wxpusher->send($content, $title, '2', 'true', $pushUid);
        
        // 如果发送失败，记录错误
        if($result !== true) {
            error_log("发送新增代理通知失败: " . json_encode($result));
            // 如果是WxPusher返回的错误对象，提取错误信息
            if(is_array($result) && isset($result['msg'])) {
                error_log("WxPusher错误: " . $result['msg']);
            }
        }
    } catch (Exception $e) {
        error_log("发送新增代理通知异常: " . $e->getMessage());
        $result = false;
    }
    
    // 记录推送状态
    $status = $result === true ? '1' : '0';
    
    // 查询用户ID
    $uidQuery = $DB->get_row("SELECT uid FROM qingka_wangke_user WHERE pushUid='$pushUid'");
    $uid = $uidQuery ? $uidQuery['uid'] : 0;
    
    $contentLog = "代理姓名：{$agentInfo['name']}, 账号：{$agentInfo['user']}, 地区：{$location}" . (isset($agentInfo['is_test']) ? " (测试)" : "");
    
    // 使用安全的SQL插入
    $safeTitle = $DB->escape($title);
    $safeContent = $DB->escape($contentLog);
    
    // 尝试插入日志，如果表已经存在
    try {
        $sql = "INSERT INTO push_logs (uid, type, title, content, status, push_time) 
               VALUES ('$uid', 'new_agent', '$safeTitle', '$safeContent', '$status', NOW())";
        
        $logResult = $DB->query($sql);
        if(!$logResult) {
            error_log("记录推送日志失败: " . $DB->error());
        }
    } catch (Exception $e) {
        error_log("记录推送日志异常: " . $e->getMessage());
    }
    
    return $result === true;
}

/**
 * 发送订单退款通知
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $pushUid 用户的推送UID
 * @param array $orderInfo 订单信息
 * @return bool 推送结果
 */
function sendOrderRefundNotice($wxpusher, $pushUid, $orderInfo) {
    global $DB;
    
    // 验证参数
    if(empty($pushUid) || !is_array($orderInfo)) {
        error_log("发送订单退款通知参数无效: pushUid=" . ($pushUid ?? 'null') . ", orderInfo=" . json_encode($orderInfo));
        return false;
    }
    
    // 确保必要的订单信息存在
    $orderInfo['oid'] = $orderInfo['oid'] ?? '未知';
    $orderInfo['kcname'] = $orderInfo['kcname'] ?? '未知课程';
    $orderInfo['fees'] = $orderInfo['fees'] ?? '0.00';
    $orderInfo['refund_reason'] = $orderInfo['refund_reason'] ?? '未提供原因';
    $orderInfo['refund_time'] = $orderInfo['refund_time'] ?? date('Y-m-d H:i:s');
    
    // 构建推送内容
    $content = "💰 " . (isset($orderInfo['is_test']) ? "[测试] " : "") . "订单退款通知\n\n";
    $content .= "您有一个订单已退款，详情如下：\n\n";
    $content .= "📋 订单编号：" . $orderInfo['oid'] . "\n";
    $content .= "📚 课程名称：" . $orderInfo['kcname'] . "\n";
    $content .= "💲 退款金额：" . $orderInfo['fees'] . " 元\n";
    $content .= "📝 退款原因：" . $orderInfo['refund_reason'] . "\n";
    $content .= "⏰ 退款时间：" . $orderInfo['refund_time'] . "\n\n";
    $content .= "退款金额将在一个小时内返还至您的账户余额，请登录系统查看详情。";
    
    $title = (isset($orderInfo['is_test']) ? '[测试] ' : '') . '订单退款通知';
    
    try {
        // 使用Wxpusher发送消息
        $result = $wxpusher->send($content, $title, '2', 'true', $pushUid);
        
        // 如果发送失败，记录错误
        if($result !== true) {
            error_log("发送订单退款通知失败: " . json_encode($result));
            // 如果是WxPusher返回的错误对象，提取错误信息
            if(is_array($result) && isset($result['msg'])) {
                error_log("WxPusher错误: " . $result['msg']);
            }
        }
    } catch (Exception $e) {
        error_log("发送订单退款通知异常: " . $e->getMessage());
        $result = false;
    }
    
    // 记录推送状态
    $status = $result === true ? '1' : '0';
    
    // 查询用户ID
    $uidQuery = $DB->get_row("SELECT uid FROM qingka_wangke_user WHERE pushUid='$pushUid'");
    $uid = $uidQuery ? $uidQuery['uid'] : 0;
    
    $contentLog = "订单:" . $orderInfo['oid'] . ", 课程:" . $orderInfo['kcname'] . ", 金额:" . $orderInfo['fees'] . (isset($orderInfo['is_test']) ? " (测试)" : "");
    
    // 使用安全的SQL插入
    $safeTitle = $DB->escape($title);
    $safeContent = $DB->escape($contentLog);
    $orderId = isset($orderInfo['is_test']) ? null : $orderInfo['oid'];
    
    // 尝试插入日志，如果表已经存在
    try {
        $sql = "INSERT INTO push_logs (uid, order_id, type, title, content, status, push_time) 
               VALUES ('$uid', " . ($orderId ? "'$orderId'" : "NULL") . ", 'order_refund', '$safeTitle', '$safeContent', '$status', NOW())";
        
        $logResult = $DB->query($sql);
        if(!$logResult) {
            error_log("记录推送日志失败: " . $DB->error());
        }
    } catch (Exception $e) {
        error_log("记录推送日志异常: " . $e->getMessage());
    }
    
    return $result === true;
}

/**
 * 发送考试开始提醒
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $pushUid 用户的推送UID
 * @param array $examInfo 考试信息
 * @return bool 推送结果
 */
function sendExamStartNotice($wxpusher, $pushUid, $examInfo) {
    global $DB;
    
    // 验证参数
    if(empty($pushUid) || !is_array($examInfo)) {
        error_log("发送考试开始提醒参数无效: pushUid=" . ($pushUid ?? 'null') . ", examInfo=" . json_encode($examInfo));
        return false;
    }
    
    // 确保必要的考试信息存在
    $examInfo['oid'] = $examInfo['oid'] ?? '未知';
    $examInfo['kcname'] = $examInfo['kcname'] ?? '未知课程';
    $examInfo['examStartTime'] = $examInfo['examStartTime'] ?? '未知时间';
    $examInfo['school'] = $examInfo['school'] ?? '未知学校';
    $examInfo['user'] = $examInfo['user'] ?? '未知账号';
    
    // 构建推送内容
    $content = "📝 " . (isset($examInfo['is_test']) ? "[测试] " : "") . "考试即将开始提醒\n\n";
    $content .= "您有一个课程将在1天后开始考试，请关注考试时间！\n\n";
    $content .= "📋 订单编号：" . $examInfo['oid'] . "\n";
    $content .= "📚 课程名称：" . $examInfo['kcname'] . "\n";
    $content .= "🏫 所属学校：" . $examInfo['school'] . "\n";
    $content .= "👤 课程账号：" . $examInfo['user'] . "\n";
    $content .= "⏰ 考试时间：" . $examInfo['examStartTime'] . "\n\n";
    $content .= "请及时登录系统确认考试详情，如有疑问请联系上级。";
    
    $title = (isset($examInfo['is_test']) ? '[测试] ' : '') . '考试即将开始提醒';
    
    try {
        // 使用Wxpusher发送消息
        $result = $wxpusher->send($content, $title, '2', 'true', $pushUid);
        
        // 如果发送失败，记录错误
        if($result !== true) {
            error_log("发送考试开始提醒失败: " . json_encode($result));
            // 如果是WxPusher返回的错误对象，提取错误信息
            if(is_array($result) && isset($result['msg'])) {
                error_log("WxPusher错误: " . $result['msg']);
            }
        }
    } catch (Exception $e) {
        error_log("发送考试开始提醒异常: " . $e->getMessage());
        $result = false;
    }
    
    // 记录推送状态
    $status = $result === true ? '1' : '0';
    
    // 查询用户ID
    $uidQuery = $DB->get_row("SELECT uid FROM qingka_wangke_user WHERE pushUid='$pushUid'");
    $uid = $uidQuery ? $uidQuery['uid'] : 0;
    
    $contentLog = "课程: " . $examInfo['kcname'] . ", 考试时间: " . $examInfo['examStartTime'] . (isset($examInfo['is_test']) ? " (测试)" : "");
    
    // 使用安全的SQL插入
    $safeTitle = $DB->escape($title);
    $safeContent = $DB->escape($contentLog);
    $orderId = isset($examInfo['is_test']) ? null : $examInfo['oid'];
    
    // 尝试插入日志，如果表已经存在
    try {
        $sql = "INSERT INTO push_logs (uid, order_id, type, title, content, status, push_time) 
               VALUES ('$uid', " . ($orderId ? "'$orderId'" : "NULL") . ", 'exam_notice', '$safeTitle', '$safeContent', '$status', NOW())";
        
        $logResult = $DB->query($sql);
        if(!$logResult) {
            error_log("记录推送日志失败: " . $DB->error());
        }
    } catch (Exception $e) {
        error_log("记录推送日志异常: " . $e->getMessage());
    }
    
    return $result === true;
}

/**
 * 获取IP地址位置信息
 * 
 * @param string $ip IP地址
 * @return string 位置信息
 */
function getIpLocation($ip) {
    if (empty($ip) || $ip == 'unknown') {
        return '未知位置';
    }
    
    // 调用IP数据云API获取位置信息
    $url = "https://app.ipdatacloud.com/v2/free_query?ip=" . urlencode($ip);
    
    // 使用curl代替file_get_contents，添加超时设置
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); // 连接超时3秒
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);       // 总超时10秒
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 不验证SSL证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不验证SSL主机
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($response === false || $httpCode != 200) {
        error_log("获取IP位置信息失败: " . ($error ? $error : "HTTP状态码: $httpCode"));
        return $ip; // 如果API失败，返回原始IP
    }
    
    $data = json_decode($response, true);
    
    if (isset($data['code']) && $data['code'] == 200 && isset($data['data'])) {
        $location = [];
        if (!empty($data['data']['province'])) {
            $location[] = $data['data']['province'];
        }
        if (!empty($data['data']['city'])) {
            $location[] = $data['data']['city'];
        }
        if (!empty($data['data']['isp'])) {
            $location[] = $data['data']['isp'];
        }
        
        $locationStr = implode(' ', array_filter($location));
        
        // 如果解析出来的位置为空，返回原始IP
        if (empty($locationStr)) {
            error_log("IP位置解析结果为空: $response");
            return $ip;
        }
        
        return $locationStr;
    }
    
    error_log("解析IP位置信息失败: " . $response);
    return $ip;
}

/**
 * 获取设备信息
 * 
 * @param string $userAgent 用户代理字符串
 * @return string 设备信息
 */
function getDeviceInfo($userAgent) {
    if (empty($userAgent)) {
        return '未知设备';
    }
    
    // 简单的设备识别逻辑
    if (stripos($userAgent, 'iPhone') !== false) {
        return 'iPhone';
    } elseif (stripos($userAgent, 'iPad') !== false) {
        return 'iPad';
    } elseif (stripos($userAgent, 'Android') !== false) {
        if (stripos($userAgent, 'Mobile') !== false) {
            return 'Android手机';
        } else {
            return 'Android平板';
        }
    } elseif (stripos($userAgent, 'Windows') !== false) {
        return 'Windows电脑';
    } elseif (stripos($userAgent, 'Macintosh') !== false) {
        return 'Mac电脑';
    } elseif (stripos($userAgent, 'Linux') !== false) {
        return 'Linux电脑';
    }
    
    return '其他设备';
}

/**
 * 发送登录安全提醒
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $pushUid 用户的推送UID
 * @param array $loginInfo 登录信息
 * @return bool 推送结果
 */
function sendLoginSecurityAlert($wxpusher, $pushUid, $loginInfo) {
    global $DB;
    
    // 验证参数
    if(empty($pushUid) || !is_array($loginInfo)) {
        error_log("发送登录安全提醒参数无效: pushUid=" . ($pushUid ?? 'null') . ", loginInfo=" . json_encode($loginInfo));
        return false;
    }
    
    // 确保必要的登录信息存在
    $loginInfo['ip'] = $loginInfo['ip'] ?? 'unknown';
    $loginInfo['device'] = $loginInfo['device'] ?? 'unknown';
    $loginInfo['time'] = $loginInfo['time'] ?? date('Y-m-d H:i:s');
    
    // 获取IP位置信息（添加超时设置）
    $ip = $loginInfo['ip'];
    $location = '未知位置';
    if(!empty($ip) && $ip != 'unknown') {
        // 先获取IP地址位置信息，再发送通知
        $location = getIpLocation($ip);
        
        // 记录日志
        error_log("登录安全IP信息获取: " . $ip . " -> " . $location);
        
        // 如果位置仍然是IP地址，再尝试一次获取位置
        if($location == $ip) {
            sleep(1); // 等待1秒后重试
            $location = getIpLocation($ip);
        }
    }
    
    // 构建推送内容
    $content = "⚠️ " . (isset($loginInfo['is_test']) ? "" : "") . "登录安全提醒\n\n";
    $content .= "您的账号刚刚在新设备或新位置登录，请确认是您本人操作\n\n";
    $content .= "📱 设备信息：" . $loginInfo['device'] . "\n";
    $content .= "🌐 登录IP：" . $loginInfo['ip'] . "\n";
    $content .= "📍 登录位置：" . $location . "\n";
    $content .= "⏰ 登录时间：" . $loginInfo['time'] . "\n\n";
    $content .= "如果这不是您的操作，请立即修改密码并联系客服。";
    
    $title = (isset($loginInfo['is_test']) ? '' : '') . '登录安全提醒';
    
    try {
        // 使用Wxpusher发送消息
        $result = $wxpusher->send($content, $title, '2', 'true', $pushUid);
        
        // 如果发送失败，记录错误
        if($result !== true) {
            error_log("发送登录安全提醒失败: " . json_encode($result));
            if(is_array($result) && isset($result['msg'])) {
                error_log("WxPusher错误: " . $result['msg']);
            }
        }
    } catch (Exception $e) {
        error_log("发送登录安全提醒异常: " . $e->getMessage());
        $result = false;
    }
    
    // 记录推送状态
    $status = $result === true ? '1' : '0';
    
    // 查询用户ID
    $uidQuery = $DB->get_row("SELECT uid FROM qingka_wangke_user WHERE pushUid='$pushUid'");
    $uid = $uidQuery ? $uidQuery['uid'] : 0;
    
    $contentLog = "设备:" . $loginInfo['device'] . ", IP:" . $loginInfo['ip'] . ", 位置:" . $location . (isset($loginInfo['is_test']) ? " (测试)" : "");
    
    // 使用安全的SQL插入
    $safeTitle = $DB->escape($title);
    $safeContent = $DB->escape($contentLog);
    
    // 尝试插入日志
    try {
        $sql = "INSERT INTO push_logs (uid, type, title, content, status, push_time) 
               VALUES ('$uid', 'security', '$safeTitle', '$safeContent', '$status', NOW())";
        
        $logResult = $DB->query($sql);
        if(!$logResult) {
            error_log("记录推送日志失败: " . $DB->error());
        }
    } catch (Exception $e) {
        error_log("记录推送日志异常: " . $e->getMessage());
    }
    
    return $result === true;
}

/**
 * 发送游客订单通知
 * 
 * @param object $wxpusher WxPusher对象
 * @param string $pushUid 用户的推送UID
 * @param array $orderInfo 订单信息
 * @return bool 推送结果
 */
function sendTouristOrderNotice($wxpusher, $pushUid, $orderInfo) {
    global $DB;
    
    // 验证参数
    if(empty($pushUid) || !is_array($orderInfo)) {
        error_log("发送游客订单通知参数无效: pushUid=" . ($pushUid ?? 'null') . ", orderInfo=" . json_encode($orderInfo));
        return false;
    }
    
    // 确保必要的订单信息存在
    $orderInfo['oid'] = $orderInfo['oid'] ?? '未知';
    $orderInfo['kcname'] = $orderInfo['kcname'] ?? '未知课程';
    $orderInfo['user'] = $orderInfo['user'] ?? '未知账号';
    $orderInfo['school'] = $orderInfo['school'] ?? '未知学校';
    $orderInfo['status'] = $orderInfo['status'] ?? '未知状态';
    $orderInfo['remarks'] = $orderInfo['remarks'] ?? '未知备注';
    $orderInfo['shoujia'] = $orderInfo['shoujia'] ?? '未知售价';
    $orderInfo['fees'] = $orderInfo['fees'] ?? '未知成本';
    $orderInfo['time'] = $orderInfo['time'] ?? date('Y-m-d H:i:s');
    
    // 构建推送内容
    $content = "📦 " . (isset($orderInfo['is_test']) ? "[测试] " : "") . "接单商城新增订单通知\n\n";
    $content .= "您有一个新的游客订单需要处理！\n\n";
    $content .= "📋 订单编号：" . $orderInfo['oid'] . "\n";
    $content .= "📚 课程名称：" . $orderInfo['kcname'] . "\n";
    $content .= "🏫 所属学校：" . $orderInfo['school'] . "\n";
    $content .= "👤 课程账号：" . $orderInfo['user'] . "\n";
    $content .= "📊 订单状态：" . $orderInfo['status'] . "\n";
    $content .= "💬 订单备注：" . $orderInfo['remarks'] . "\n";
    $content .= "💰 订单售价：" . $orderInfo['shoujia'] . "\n";
    $content .= "💲 订单成本：" . $orderInfo['fees'] . "\n";
    $content .= "⏰ 下单时间：" . $orderInfo['time'] . "\n\n";
    $content .= "请及时登录系统处理订单。";
    
    $title = (isset($orderInfo['is_test']) ? '[测试] ' : '') . '接单商城订单通知';
    
    try {
        // 使用Wxpusher发送消息
        $result = $wxpusher->send($content, $title, '2', 'true', $pushUid);
        
        // 如果发送失败，记录错误
        if($result !== true) {
            error_log("发送接单商城订单通知失败: " . json_encode($result));
            if(is_array($result) && isset($result['msg'])) {
                error_log("WxPusher错误: " . $result['msg']);
            }
        }
    } catch (Exception $e) {
        error_log("发送接单商城订单通知异常: " . $e->getMessage());
        $result = false;
    }
    
    // 记录推送状态
    $status = $result === true ? '1' : '0';
    
    // 查询用户ID
    $uidQuery = $DB->get_row("SELECT uid FROM qingka_wangke_user WHERE pushUid='$pushUid'");
    $uid = $uidQuery ? $uidQuery['uid'] : 0;
    
    $contentLog = "订单:" . $orderInfo['oid'] . ", 课程:" . $orderInfo['kcname'] . ", 状态:" . $orderInfo['status'] . (isset($orderInfo['is_test']) ? " (测试)" : "");
    
    // 使用安全的SQL插入
    $safeTitle = $DB->escape($title);
    $safeContent = $DB->escape($contentLog);
    $orderId = isset($orderInfo['is_test']) ? null : $orderInfo['oid'];
    
    // 尝试插入日志
    try {
        $sql = "INSERT INTO push_logs (uid, order_id, type, title, content, status, push_time) 
               VALUES ('$uid', " . ($orderId ? "'$orderId'" : "NULL") . ", 'tourist_order', '$safeTitle', '$safeContent', '$status', NOW())";
        
        $logResult = $DB->query($sql);
        if(!$logResult) {
            error_log("记录推送日志失败: " . $DB->error());
        }
    } catch (Exception $e) {
        error_log("记录推送日志异常: " . $e->getMessage());
    }
    
    return $result === true;
}

// 判断是否是推送相关的API请求并处理
$pushApiActions = [
    // 基本推送设置
    'getPushSettings', 
    'savePushSettings', 
    
    // 绑定相关
    'getBindQrcode',
    'checkBindStatus', 
    'unbindPush', 
    
    // 测试推送
    'testPush',
    'testBalanceLow', 
    'testLoginSecurityPush',
    'testLoginSecurityAlert',
    
    // 日志和记录
    'getPushLogs',
    'getLoginRecords',
    'recordLogin',
    
    // 公告相关
    'getLatestAnnouncement', 
    'sendAnnouncementPush', 
    'sendSystemNoticePush', 
    'get_announcements',
    
    // 余额相关
    'sendBalanceLowAlert', 
    'checkBalanceAndAlert',
    'manualBalanceCheck',
    

    
    // 订单异常通知
    'testOrderExceptionNotice',
    
    // 订单退款通知
    'testOrderRefundNotice',
    
    // 新增代理通知
    'testNewAgentNotice',
    
    // 考试开始提醒
    'sendExamStartNotice',
    'testExamStartNotice',
    
    // 测试游客订单通知
    'testTouristOrderNotice'
];

if (isset($act) && in_array($act, $pushApiActions)) {
    try {
        // 尝试处理推送API请求
        $handled = handle_push_api($act);
        if (!$handled) {
            error_log("推送API处理失败: $act");
        }
    } catch (Exception $e) {
        error_log("推送API处理异常: " . $e->getMessage());
        exit(json_encode(['code' => -1, 'msg' => '系统错误: ' . $e->getMessage()]));
    }
}
// 如果没有匹配的推送API操作，让脚本继续执行其他代码 